import os
from openpyxl import load_workbook,Workbook
import sys

arguments = sys.argv
run_count = 1
for i in range(len(arguments)):
    if arguments[i] == '--dir':
        swift2path=arguments[i+1]
        Date = swift2path[swift2path.rfind('/') + 1:]
    if arguments[i] == '--run-count':
        run_count = int(arguments[i+1])
    if arguments[i] == '--run-case':
        name=arguments[i+1]
def variable_exists(var_name):
    try:
        exec(var_name)
    except NameError:
        return False
    else:
        return True
if not variable_exists("swift2path"):
    sys.exit()

def runCmd(cmd):
    result = os.popen(cmd).read()
    print(cmd)
    print(result+"\n\n")
    with open(f"swift_{Date}_log.txt", "a") as file:
        file.writelines(cmd+"\n")
    with open(f"swift_{Date}_log.txt", "a") as file:
        file.writelines(result+"\n")
    return result

def is_excel_sheet_empty(file_path, sheet_name):
    try:
        workbook = load_workbook(filename=file_path)
        sheet = workbook[sheet_name]
        if sheet.max_row == 1 and sheet.max_column == 1 and sheet.cell(row=1, column=1).value is None:
            return True
        else:
            return False
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return None
def is_excel_file_exists(file_path):
    try:
        workbook = load_workbook(filename=file_path)
        return True
    except FileNotFoundError:
        return False
def run():
    print("---------------------------------------")
    if not is_excel_file_exists(f'swift_data_{Date}.xlsx'):
        workbook = Workbook()
        sheet = workbook.active
        data = ["case"]
        for i in range(run_count):
            data.append(f"data{i}")
        data.append(f"average")
        sheet.append(data)
        workbook.save(f'swift_data_{Date}.xlsx')

    workbook = load_workbook(f'swift_data_{Date}.xlsx')
    sheet = workbook['Sheet']
    with open(f"swift_{Date}_error.txt", "w") as file:
        pass
    print(name)
    test_data = {}
    with open(f"swift_{Date}_log.txt", "a") as file:
        file.writelines(name+"\n")
    with open(f"swift_{Date}_error.txt", "a") as file:
        file.writelines(name+"\n")
    for i in range(run_count):
        cmd = f"{swift2path}/{name}"
        result = runCmd(cmd)
        if "error" in result or "Signal" in result or "TypeError" in result:
            with open(f"swift_{Date}_error.txt", "a") as file:
                file.writelines(result+"\n")
        result = result.split("\n")
        for value in result:
            if " - " in value or "Splay:" in value or "SplayLatency:" in value:
                value = value.split("\t")
            else:
                continue
            if not value[0] in test_data:
                test_data[value[0]] = []
            test_data[value[0]].append(value[1])
    for itme in test_data:
        data = []
        data.append(itme)
        sum = 0
        for value in test_data[itme]:
            data.append(round(float(value),3))
            sum += round(float(value),3)
        average=round(sum/len(test_data[itme]),3)
        data.append(average)
        sheet.append(data)    
        workbook.save(f'swift_data_{Date}.xlsx')
    print("---------------------------------------\n")
run()
